package com.hayukleung.voiceclient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;

import android.os.Bundle;
import android.os.Message;

import com.hayukleung.util.Constants;
import com.hayukleung.util.LogMgr;

public class UDPServer extends Thread
{
  private static final String TAG = "UDPServer";
  DatagramPacket packet;
  public static MessageActivity message;

  // constructor
  public UDPServer(DatagramPacket packet)
  {
    this.packet = packet;
  }

  @Override
  public void run()
  {
    // received broadcast from server: [username,filename,poolid]
    String string = new String(packet.getData()).trim();
    LogMgr.writeLog(TAG, string, LogMgr.INFO);
    String username = string.split(Constants.COMMA)[0];
    String filename = string.split(Constants.COMMA)[1];
    if (new File(Constants.BASE_DIR, filename).exists())
    {
      return;
    }
    try
    {
      Socket socket = new Socket(Constants.SERVER_IPV4, Constants.SERVER_TCP_PORT_INT);
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();
      // download request token: [get,filename]
      String request = Constants.REQ_DOWNLOAD + Constants.COMMA + filename;
      out.write(request.getBytes());
      out.flush();
      LogMgr.writeLog(TAG, request, LogMgr.INFO);
      // received reply from server: [ok,filesize]
      byte[] reply = new byte[100];
      in.read(reply);
      LogMgr.writeLog(TAG, new String(reply), LogMgr.INFO);
      long filesize = Long.parseLong(new String(reply).trim().split(Constants.COMMA)[1]);
      // send [ok] to server
      out.write(Constants.REPLY_OK.getBytes());
      out.flush();
      
      FileOutputStream fout = new FileOutputStream(new File(Constants.BASE_DIR, filename));
      int len = 0;
      long totalLen = 0;
      byte[] temp = new byte[1 * Constants.K];
      while (-1 != (len = in.read(temp)))
      {
        fout.write(temp, 0, len);
        totalLen += len;
        if (totalLen >= filesize)
        {
          break;
        }
      }
      fout.close();
      socket.close();
      Message msg = new Message();
      Bundle data = new Bundle();
      data.putString("username", username);
      data.putString("filename", filename);
      msg.setData(data);
      message.handler.sendMessage(msg);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public static void openServer() throws Exception
  {
    DatagramSocket socket = new DatagramSocket(Constants.CLIENT_UDP_PORT_INT);

    while (true)
    {
      byte[] bytes = new byte[1 * Constants.K];
      DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
      socket.receive(packet);
      new UDPServer(packet).start();

    }
  }
}
